package com.itheima.bakery.demos.web.service;

import com.itheima.bakery.demos.web.model.Category;
import com.itheima.bakery.demos.web.Repositories.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.persistence.EntityNotFoundException;
import javax.sql.DataSource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class CategoryService {

    private static final Logger logger = LoggerFactory.getLogger(CategoryService.class);
    private final CategoryRepository categoryRepository;

    @Autowired
    public CategoryService(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    public List<Category> findAllCategories() {
        logger.info("Fetching all categories");
        return categoryRepository.findAll();
    }

    public Optional<Category> findCategoryById(Integer id) {
        logger.info("Finding category with ID: {}", id);
        return categoryRepository.findById(id);
    }

    @Transactional
    public  Category saveCategory(@Valid Category category) {
        if (category.getCategoryID() != null && category.getCategoryName().isEmpty()) {
            throw new IllegalArgumentException("Category name cannot be null or empty");
        }
        return categoryRepository.save(category);
    }

    @Transactional
    public void deleteCategory(Integer id) {
        logger.info("Deleting category with ID: {}", id);
        categoryRepository.deleteById(id);
    }

    @Transactional
    public Category updateCategory(Integer id, @Valid Category category) {
        if (!categoryRepository.existsById(id)) {
            throw new EntityNotFoundException("Category not found");
        }
        category.setCategoryID(id);  // Ensure the ID is set
        logger.info("Updating category with ID: {}", id);
        return categoryRepository.save(category);
    }
    @Autowired
    private JpaProperties jpaProperties;
    @Autowired
    private HibernateProperties hibernateProperties;

    private Map<String, Object> getVendorProperties() {
        return hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
    }
}
